Read COVID-19 data

data <- read_csv("../COVID-19/covid_19_data.csv")
## Parsed with column specification:
## cols(
##   SNo = col_double(),
##   ObservationDate = col_character(),
##   `Province/State` = col_character(),
##   `Country/Region` = col_character(),
##   `Last Update` = col_character(),
##   Confirmed = col_double(),
##   Deaths = col_double(),
##   Recovered = col_double()
## )

Some data transformations to make getting geocodes easier

# get unique locations
locations <- data %>%
  rename(state = `Province/State`, country = `Country/Region`) %>%
  group_by(state, country) %>%
  summarise(
    total_cases = sum(Confirmed),
    total_deaths = sum(Deaths),
    total_recovered = sum(Recovered)
  )

# clean_states <- locations %>%
#   group_by(state) %>%
#   summarise(n = length(unique(country))) %>%
#   filter(n == 1) %>%
#   select(state) %>%
#   unlist()
# 
# # get lat lon for states
# geo_info <- lapply(clean_states, function(x){
#   geo <- tryCatch(
#     geocode(x),
#     error = function(e) {
#       return(tibble(lon = NA, lat = NA))
#     },
#     warning = function(w) {
#       return(tibble(lon = NA, lat = NA))
#     }
#   )
#   list(
#     state = x,
#     lon = geo$lon,
#     lat = geo$lat
#   )
# })
# 
# geo_info_df <- lapply(geo_info, function(x){
#   tibble(state = x$state, lon = x$lon, lat = x$lat)
#   }
# ) %>%
#   bind_rows()
# 
# write_csv(geo_info_df, path = "data/covid-19_geo_info.csv")

Prepare data for plotting map

# combine location with data
loc <- read_csv("data/covid-19_geo_info.csv") %>%
  filter(!is.na(lon) | !is.na(lat))
## Parsed with column specification:
## cols(
##   state = col_character(),
##   lon = col_double(),
##   lat = col_double()
## )
plt_data <- locations %>%
  left_join(loc, by = "state") %>%
  group_by(lon, lat) %>%
  summarise(
    country = unique(country)[1],
    state = unique(state)[1],
    total_cases = sum(total_cases),
    total_deaths = sum(total_deaths),
    total_recovered = sum(total_recovered)
  )

barplot_data <- plt_data %>%
  ungroup() %>%
  select(state, lon, lat, total_cases, total_deaths, total_recovered) %>%
  gather(key = case_type, value = n, -lon, -lat, -state)

Plot the map

leaflet(plt_data) %>% addTiles() %>%
  addCircleMarkers(
    ~lon, ~lat,
    popup = lapply(
      plt_data$state,
      function(i) {
        x = barplot_data %>% filter(state == i)
        plt <- ggplot(x, aes(x = case_type, y = n, fill = case_type)) + 
          geom_bar(stat = "identity", width = 0.2) + 
          coord_flip() + 
          theme_minimal() +
          guides(fill = FALSE) +
          ggtitle(paste0("Covid-19 count for ", unique(x$state)))
        ggplotly(plt) %>%
          as.tags() %>%
          {tags$div(style="width:600px;height:400px", .)} %>%
          as.character()
      }
    ),
    clusterOption=markerClusterOptions(),
    label = ~as.character(state),
    radius = ~ log(total_cases)
  ) %>%
  onRender(
"
function(el,x) {
  this.on('popupopen', function() {HTMLWidgets.staticRender();})
}
") %>%
  add_deps("plotly") %>%
  htmltools::attachDependencies(plotly:::plotlyMainBundle(), append = TRUE) %>%
  htmltools::attachDependencies(crosstalk::crosstalkLibs(), append = TRUE) %>%
  browsable()
## Warning in validateCoords(lng, lat, funcName): Data contains 1 rows with either
## missing or invalid lat/lon values and will be ignored
leaflet(plt_data) %>% addTiles() %>%
  addCircleMarkers(
    ~lon, ~lat,
    popup = lapply(
      plt_data$state,
      function(i) {
        x = barplot_data %>% filter(state == i)
        plt <- ggplot(x, aes(x = state, y = n, fill = case_type)) + 
          geom_col(width = 0.3) + 
          coord_flip() + 
          theme_minimal() +
          ggtitle(paste0("Covid-19 count for ", unique(x$state))) +
          guides(
            fill = FALSE
          )
        ggplotly(plt) %>%
          as.tags() %>%
          {tags$div(style="width:600px;", .)} %>%
          as.character()
      }
    ),
    # clusterOption=markerClusterOptions(),
    label = ~as.character(state),
    radius = ~ log(total_cases)
  ) %>%
  onRender(
"
function(el,x) {
  this.on('popupopen', function() {HTMLWidgets.staticRender();})
}
") %>%
  add_deps("plotly") %>%
  htmltools::attachDependencies(plotly:::plotlyMainBundle(), append = TRUE) %>%
  htmltools::attachDependencies(crosstalk::crosstalkLibs(), append = TRUE) %>%
  browsable()
## Warning in validateCoords(lng, lat, funcName): Data contains 1 rows with either
## missing or invalid lat/lon values and will be ignored
# width:600px;